package com.yuandengta.yomall.product.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yuandengta.common.to.SkuReductionTO;
import com.yuandengta.common.utils.R;
import com.yuandengta.yomall.product.entity.*;
import com.yuandengta.yomall.product.feign.CouponFeignService;
import com.yuandengta.yomall.product.feign.SeckillFeignService;
import com.yuandengta.yomall.product.service.*;
import com.yuandengta.yomall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandengta.common.utils.PageUtils;
import com.yuandengta.common.utils.Query;

import com.yuandengta.yomall.product.dao.SkuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存spu对应的sku
     * @param spuInfoEntity
     * @param skus
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSkuInfo(SpuInfoEntity spuInfoEntity, List<Skus> skus) {
        skus.forEach(sku -> {
            // 保存sku基本信息
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setSaleCount(0L);
            String defaultImage = "";
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == 1) {
                    defaultImage = image.getImgUrl();
                }
            }
            skuInfoEntity.setSkuDefaultImg(defaultImage);
            this.save(skuInfoEntity);

            // 批量保存sku图片
            Long skuId = skuInfoEntity.getSkuId();
            List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(image -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuId);
                skuImagesEntity.setDefaultImg(image.getDefaultImg());
                skuImagesEntity.setImgUrl(image.getImgUrl());
                return skuImagesEntity;
            }).filter(skuImagesEntity -> {
                return !StringUtils.isEmpty(skuImagesEntity.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);

            // 批量保存sku属性值
            List<SkuSaleAttrValueEntity> collect = sku.getAttr().stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuId);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(collect);

            // 保存优惠，满减等信息
            SkuReductionTO skuReductionTO = new SkuReductionTO();
            BeanUtils.copyProperties(sku, skuReductionTO);
            skuReductionTO.setSkuId(skuId);
            if (skuReductionTO.getFullCount() > 0
                    || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                R r = couponFeignService.savaReduction(skuReductionTO);
                if (r.getCode() != 0) {
                    // TODO 数据一致性问题：分布式事务
                    log.error("调用远程服务 yomall-coupon 保存SKU优惠信息失败");
                }
            }
        });
    }

    /**
     * SKU 检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String brandId = (String)params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String)params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        String min = (String)params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }

        String max = (String)params.get("max");
        if (!StringUtils.isEmpty(max) && !"0".equalsIgnoreCase(max)) {
            queryWrapper.le("price", max);
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 查询出当前spuId对应的所有sku信息
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> entities = this.list(
                new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return entities;
    }

    /**
     * 商品详情
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVO item(Long skuId) throws Exception {
        SkuItemVO skuItemVO = new SkuItemVO();

        // 异步编排
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // 1.sku基本信息 pms_sku_info
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVO.setSkuInfo(skuInfo);
            return skuInfo;
        }, executor);

        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 2.spu销售属性组合
            List<SkuSaleAttrVO> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVO.setSaleAttrs(saleAttrs);
        }, executor);

        CompletableFuture<Void> descFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 3.spu商品介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVO.setSpuDesc(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 4.spu规格参数
            List<SpuAttrGroupVO> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(
                    res.getCatalogId(), res.getSpuId());
            skuItemVO.setGroupAttrs(groupAttrs);
        }, executor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            // 5.sku图片信息 pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            skuItemVO.setImages(images);
        }, executor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            // 查询当前sku是否参与秒杀优惠
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillSkuVO seckillSkuVO = r.getData("data", new TypeReference<SeckillSkuVO>() {
                });
                skuItemVO.setSeckillInfo(seckillSkuVO);
            } else {
                log.error("远程调用 yomall-seckill 获取商品秒杀信息失败");
            }
        }, executor);


        // 等待所有任务执行完
        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture, seckillFuture).get();

        // TODO 查询库存
        skuItemVO.setHasStock(true);

        return skuItemVO;
    }

    /**
     * 创建静态化页面
     * @param skuId
     */
    @Override
    public void createHtml(Long skuId) {
        // 新建线程处理静态化页面
        executor.submit(() -> {
            PrintWriter writer = null;
            try {
                // 获取页面数据
                SkuItemVO skuItemVO = item(skuId);

                // 创建thymeleaf上下文对象
                Context context = new Context();
                // 把数据放入上下文对象
                context.setVariable("skuItemVO", skuItemVO);

                // 创建输出流，指定输出目的地
                // 上线后，这个目的地应该配置为 nginx 的一个资源目录
                File file = new File("C:\\" + skuId + ".html");
                writer = new PrintWriter(file);

                // 执行页面静态化方法
                templateEngine.process("item", context, writer);
            } catch (Exception e) {
                log.error("页面静态化出错：{}", e, skuId);
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
        });
    }

}